package mortal.game.manager
{
	import com.gengine.global.*;
	import com.gengine.ui.timer.*;
	
	import flash.events.*;
	import flash.utils.*;
	
	import mortal.game.events.*;
	
	public class ClockManager extends EventDispatcher
	{
		private var _gameClock:GameClock;
		private var _timeMap:Dictionary;
		private var _serverDate:Date;
		
		public function ClockManager()
		{
			this._timeMap = new Dictionary();
			if (_instance != null)
			{
				throw new Error("ClockManager 单例");
			}
		}
		
		public function setNowTimer(date:Date) : void
		{
			if (this._gameClock == null)
			{
				this._gameClock = new GameClock();
				this._gameClock.enterFrameHandler = enterFrameHandler;
				this._gameClock.x = 100;
				this._gameClock.y = 90;
			}
			this._gameClock.time = date;
			this._serverDate = new Date(this._gameClock.nowDate.time);
		}
		
		private function enterFrameHandler(date:Date) : void
		{
			if (this._serverDate.date < date.date || this._serverDate.month < date.month || this._serverDate.fullYear < this._serverDate.fullYear)
			{
				this._serverDate.time = date.time;
				dispatchEvent(new TimeEvent(TimeEvent.DateChange));
			}
			
			for (var item:Object in this._timeMap)
			{
				item = item as Date;
				if (item)
				{
					if (item.time <= date.time)
					{
						this._timeMap[item]();
						this.removeDateCall(item as Date);
					}
				}
			}
		}
		
		private function removeDateCall(date:Date) : void
		{
			if (this._timeMap[date])
			{
				this._timeMap[date] = null;
				delete this._timeMap[date];
			}
		}
		
		private static var _instance:ClockManager;
		public static function get instance() : ClockManager
		{
			if (_instance == null){
				_instance = new (ClockManager);
			}
			
			return (_instance);
		}
	}
}